import { defineConfig, loadEnv } from 'vite'
import { fileURLToPath, URL } from 'node:url'
import process from 'node:process'
import vue from '@vitejs/plugin-vue'

// 按需导入 Element-plus 模块
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// 构建文件可视化分析
import { visualizer } from 'rollup-plugin-visualizer'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  return {
    base: loadEnv(mode, process.cwd()).VITE_BASE_URL,
    define: {
      // 启用生产环境构建下激活不匹配的详细警告
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'true' // vue 3.4+
    },
    plugins: [
      vue(),
      // Element-plus 按需导入模块
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver()]
      }),
      visualizer({
        open: true,
        filename: 'stats.html',
        gzipSize: true,
        brotliSize: true
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@v': fileURLToPath(new URL('./src/views', import.meta.url)),
        '@c': fileURLToPath(new URL('./src/components', import.meta.url))
      }
    },
    server: {
      host: '0.0.0.0',
      port: 3002,
      proxy: {
        '/api': {
          target: 'http://192.168.10.78:8080/',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    esbuild: {
      drop: ['console', 'debugger'] //去除生产环境下的console.xxxx和debugger
    },
    build: {
      // chunkSize 限制和警告
      chunkSizeWarningLimit: 500 * 1024, // 设置为500KB，超过此大小的chunk会发出警告
      // rollup配置
      rollupOptions: {
        output: {
          entryFileNames: 'js/[name]-[hash].js',
          chunkFileNames: 'js/[name]-chunk-[hash].js',
          assetFileNames: (assetInfo) => {
            if (assetInfo.name.endsWith('.css')) {
              return 'css/[name]-[hash].css'
            }
            const imgExts = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.svg', '.ico']
            if (imgExts.some((ext) => assetInfo.name.endsWith(ext))) {
              return 'img/[name]-[hash].[ext]'
            }
            return 'assets/[name]-[hash].[ext]'
          },
          manualChunks(modulePath) {
            if (modulePath.includes('node_module')) {
              return 'vendor'
            }
          }
        }
      }
    }
  }
})
